package com.zhao.commonUtil;


import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Description: <br/>
 * Copyright (c) ，2021 ， 赵 <br/>
 * This program is protected by copyright laws. <br/>
 * Date： 2021/1/6 10:07
 *
 * @author 柒柒
 * @version : 1.0
 * @Update [序号][日期YYYY-MM-DD] [更改人姓名][变更描述]
 */

public class ConnectionManager {

    static DataSource dataSourcec = new DataSource();

    static String url = "jdbc:mysql://node01:3306/fz_bigscreen?useUnicode=true&characterEncoding=utf-8";
    static String user = "root";
    static String password = "123456";

    static String jdbcDriver = "com.mysql.jdbc.Driver";

    static {
        PoolProperties poolProperties = new PoolProperties();
        try{
            //设置URL
            poolProperties.setUrl(url);
            //设置驱动名
            poolProperties.setDriverClassName(jdbcDriver);
            //设置数据库用户名
            poolProperties.setUsername(user);
            //设置数据库密码
            poolProperties.setPassword(password);
            //设置初始化连接数
            poolProperties.setInitialSize(10);

            poolProperties.setMaxActive(10);
            poolProperties.setMinIdle(5);
            poolProperties.setMinIdle(10);
            poolProperties.setMaxWait(3000);
            poolProperties.setMinEvictableIdleTimeMillis(5 * 60 *1000);
            poolProperties.setTimeBetweenEvictionRunsMillis(10 * 60 * 1000);
            poolProperties.setTestOnBorrow(true);

            dataSourcec.setPoolProperties(poolProperties);
        }catch (Exception e){
            throw new RuntimeException("初始化数据库连接池失败");
        }
    }

    /**
     * 获取连接
     * @return
     */
    public static final Connection getConnnection(){
        Connection conn = null;
        try {
            conn = dataSourcec.getConnection();
        }catch (SQLException e){
            throw new RuntimeException("获取数据库连接失败");
        }
        return conn;
    }

    //关闭连接,伪关闭
    public static void closeAll(ResultSet rs, Statement stmt, Connection conn){
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}












